package com.sq.springbootvue.controller;

import com.sq.springbootvue.entity.User;
import com.sq.springbootvue.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: vue-element-template-backend
 * @description:
 * @author: 翁仕权
 * @create: 2020-06-27 17:19
 */
@Controller
public class LoginShiroController {

    @Autowired
    private UserService userService;


    /**
     * 登录逻辑处理
     */
    @RequestMapping("/vue-admin-template/user/login")
    @ResponseBody
    public Map login(@RequestBody Map<String, Object> map) {

        /**
         * 使用Shiro编写认证操作
         */
        //1.获取当前用户
        Subject subject = SecurityUtils.getSubject();
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        HashMap<String, Object> response = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();

        //3.执行登录方法
        try {
            subject.login(token);//如果没有异常就ok

            User u = new User();
            u  = userService.getById(1);
            responseData.put("u",u);
            responseData.put("token",1);
            response.put("code",20000);
            response.put("message","登录成功");
            response.put("data",responseData);
            //登录成功
            return response;


        } catch (UnknownAccountException e) {
            //e.printStackTrace();
            //登录失败:用户名不存在
            response.put("code",20001);
            response.put("message", "登录失败,用户名不存在");
            return response;
        } catch (IncorrectCredentialsException e) {
            //e.printStackTrace();
            //登录失败:密码错误
            response.put("code",20002);
            response.put("message", "登录失败,密码错误");
            return response;
        }

    }
}
